package cn.codeforfun.common;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

/**
 * Created by Administrator on 2016/12/18 0018.
 */
public class FileUtil {
    public static void download(File file, HttpServletResponse response) {
        String fileName = file.getName();
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        response.setContentType("image/*");
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        OutputStream outp = null;
        FileInputStream in = null;
        try {
            outp = response.getOutputStream();
            in = new FileInputStream(file);
            byte[] b = new byte[1024];
            int i = 0;
            while ((i = in.read(b)) > 0) {
                outp.write(b, 0, i);
            }
            outp.flush();
        } catch (Exception e) {
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outp != null) {
                try {
                    outp.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void upload(MultipartFile mpfile, String path) throws IOException {
        byte[] bytes = mpfile.getBytes();
        String fileDir = path;
        File file = new File(fileDir);
        if (!file.exists()) {
            file.mkdirs();
        }
        String suffix = mpfile.getOriginalFilename().substring(mpfile.getOriginalFilename().lastIndexOf(".") + 1);
        String fileName = String.valueOf(System.currentTimeMillis()) + "." + suffix;
        OutputStream outputStream = new FileOutputStream(file.getPath() + File.separator + fileName);
        outputStream.write(bytes);
        outputStream.flush();
        outputStream.close();
    }
}
